import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";

import Layout from "@/views/Layout.vue";
import Login from "@views/Login.vue";
import { localCache } from "@/utils/storage";
import { ACCESS_TOKEN_KEY } from "@/enums/cacheEnum";
import { addRoutes, clearRoutes } from "@/filterAsnycRouter";
import { userStore } from "@/stores/modules/user";
import { menuStore } from "@/stores/modules/menu";

export const routesList: RouteRecordRaw[] = [
  {
    name: "ChineseAlmanac",
    path: "/ChineseAlmanac",
    component: () => import("@/views/ChineseAlmanac/index.vue"),
    meta: {
      label: "日历管理",
      key: "ChineseAlmanac",
    },
  },
  {
    name: "Log",
    path: "/Log",
    component: () => import("@views/Log.vue"),
    meta: {
      label: "日志管理",
      key: "Log",
    },
  },

  {
    name: "Demo",
    path: "/Demo",
    component: () => import("@views/Demo.vue"),
    meta: {
      label: "日历管理",
      key: "Demo",
    },
  },
  {
    name: "Dialog",
    path: "/Dialog",
    component: () => import("@views/Dialog.vue"),
    meta: {
      label: "弹框管理",
      key: "Dialog",
    },
  },
  {
    name: "Maps",
    path: "/Maps",
    component: () => import("@views/map/Maps.vue"),
    meta: {
      label: "日历管理",
      key: "Maps",
    },
  },
  {
    name: "Http",
    path: "/Http",
    component: () => import("@views/Http.vue"),
    meta: {
      label: "请求管理",
      key: "Http",
    },
  },
  {
    name: "SQL",
    path: "/SQL",
    component: () => import("@views/SQL.vue"),
    meta: {
      label: "日历管理",
      key: "SQL",
    },
  },
  {
    name: "window",
    path: "/window",
    component: () => import("@views/window.vue"),
    meta: {
      label: "窗口管理",
      key: "window",
    },
  },
  {
    path: "/child",
    name: "child",
    component: () => import("@/views/childView.vue"),
    meta: {
      label: "窗口管理",
      windowLabel: "child",
      parentWindow: "main",
    },
  },
];
const routes: RouteRecordRaw[] = [
  {
    name: "Login",
    path: "/login",
    component: Login,
    meta: {
      label: "登录认证",
      key: "login",
    },
  },
  {
    path: "/",
    name: "Layout",
    component: Layout,
    meta: { windowLabel: "main", label: "/" },
    children: routesList,
    redirect: "ChineseAlmanac",
  },
  {
    name: "404",
    path: "/:pathMatch(.*)",
    component: () => import("@/components/NotFound.vue"),
    meta: {
      label: "找不到页面",
    },
  },
];
const whiteList: any = [];
// 创建路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

let registerRouteFresh1 = true; //记录路由动态加载的状态
let registerRouteFresh2 = true;

router.beforeEach(async (to, from: any, next) => {
  const windowLabel = to.meta.windowLabel;
  if (windowLabel && typeof windowLabel === "string") {
    const currentWindow = window.__TAURI__?.window.getCurrent();
    if (currentWindow) {
      currentWindow.setLabel(windowLabel).catch(console.error);
    }
  }
  const user_store = userStore();
  const menu_store = menuStore();
  const token: string = localCache.getCache(ACCESS_TOKEN_KEY);
  if (to.name !== "Login" && !token) {
    next({ path: "/login" });
  } else {
    if (whiteList.includes(from.name)) {
      next();
    } else {
      if (to.name == "Login") {
        setTimeout(() => {
          clearRoutes(menu_store, router, user_store);
        }, 2000);
        user_store.clearToken();
        user_store.clearUser();
      }
      // 从login 页面进入到 homepage  如果你的数据是加载login页面获取，该if可不要
      if (from.name === "Login" && registerRouteFresh1) {
        addRoutes(menu_store, router, user_store, true);
        next({ ...to, replace: true });
        //{ ...to, replace: true }  因为动态添加路由时，可能会存在添加未完成时路由发生跳转
        //  此时通过上述代码可重定向到beforeEach执行之前，再次执行加载
        registerRouteFresh1 = false;
      }
      // 本地刷新的时候执行
      if (!from.name && registerRouteFresh2) {
        // 如果首次登录,进入菜单数据正常,直接进行动态添加路由
        if (user_store.routerList && user_store.routerList.length > 0) {
          addRoutes(menu_store, router, user_store, false);
        } else {
          // 关闭浏览器,再次进入token存在,菜单数据存在缓存,重新设置菜单数据并进行动态添加路由
          user_store.setMenus().then(() => {
            addRoutes(menu_store, router, user_store, false);
          });
        }
        // next({ ...to, replace: true });
        next({
          path: `${to.path}`,
        });
        registerRouteFresh2 = false;
      } else {
        next();
      }
    }
  }
});

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  if (isChunkLoadFailed) {
    location.reload();
  }
});

export default router;
